 <template>
	<div>
		<el-form ref="refForm" :rules="rules"  :inline="true" :model="formInline" size="mini" label-width="100px">
			<el-row class="mb10">
				<el-form-item prop="receiver" :label="outTypeTitle + '人：'" style="margin-bottom: 10px" >
					<el-input v-model="formInline.receiver" placeholder="请输入..." style="width:198px;"></el-input>
					<!-- <el-select filterable allow-create v-model="formInline.receiver" placeholder="请选择...">
						<el-option v-for="item in options.tqrs" :key="item.value" :label="item.label" :value="item.value"> </el-option>
					</el-select> -->
				</el-form-item>
				<el-form-item :label="outTypeTitle + '单位：'" style="margin-bottom: 10px"  prop="receiverOrgan">
					<el-input v-model="formInline.receiverOrgan" placeholder="请输入..." style="width:198px;"></el-input>
					<!-- <el-select filterable allow-create v-model="formInline.receiverOrgan" placeholder="请选择...">
						<el-option v-for="item in options.tqdws" :key="item.value" :label="item.label" :value="item.value"> </el-option>
					</el-select> -->
				</el-form-item>
				<el-form-item label="联系电话：" style="margin-bottom: 10px"  prop="receiverPhone">
					<el-input v-model="formInline.receiverPhone" placeholder="请输入..." style="width:198px;"></el-input>
				</el-form-item>
				<el-form-item required="true" label="存放位置：" prop="location"  style="margin-bottom: 10px;" @click="onLocation" v-if="outType == '6'">
					<el-input v-model="formInline.location" style="width:198px" placeholder="请选择..."> </el-input>
				</el-form-item>
				<el-form-item label="保存期限：" prop="returnTime" v-if="outType == '6'" style="margin-bottom: 10px !important;">
					<el-date-picker format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD  HH:mm:ss" style="width:198px;" v-model="formInline.returnTime" type="datetime" placeholder="请选择..."> </el-date-picker>
				</el-form-item>
				<el-form-item label="回库时间：" prop="returnTime"   v-if="outType == '1' || outType == '2'" style="margin-bottom: 10px !important;">
					<el-date-picker format="YYYY-MM-DD  HH:mm:ss" value-format="YYYY-MM-DD  HH:mm:ss" style="width:198px;" v-model="formInline.returnTime" type="datetime" placeholder="请选择..."> </el-date-picker>
				</el-form-item>
			</el-row>
			<el-row>
				<el-form-item  :label="outTypeTitle + '意见：'" style="width: 100%;"  prop="remark" class="mb15">
					<el-input v-model="formInline.remark" type="textarea" placeholder="请输入..."></el-input>
				</el-form-item>
			</el-row>
			<el-row>
				<el-form-item label="上传凭证：" required="true" show-message="" style="width: 100%; margin-top: 10px">
					<el-upload
						:action="`${baseUrl}/common/upload/img`"
						:headers="customsHeaders"
						:data="{
							ty: '3',
							id: '0',
						}"
						list-type="picture-card"
						:auto-upload="true"
						:on-success="onSuccess"
						:file-list="fileList"
						:before-remove="handleRemove"
						:on-preview="handlePictureCardPreview"
					>
					<template #default>
								<i class="el-icon-plus"></i>
							</template>
							<template #tip>
								<div
									class="el-upload el-upload--picture-card el-icon-camera"
									@click="onCameraInfo"
									style="margin-left: 10px; font-size: 30px; color: #8c939d"
								></div>
							</template>
					</el-upload>
					<el-dialog v-model="dialogVisible">
						<el-image style="width: 800px; height: 600px" he :src="dialogImageUrl" alt="" />
					</el-dialog>
					<!-- <el-button type="primary" icon="el-icon-edit" @click="addimgs" align="center" size="medium">add images</el-button> -->
				</el-form-item>
			</el-row>
		</el-form>
		<el-drawer
			v-model="drawer"
			title="选择位置 "
			direction="rtl"
			size="80%"
			:before-close="
				() => {
					drawer = false;
				}
			"
		>
			<store-index :isShow="1" :isInOut="1" :height="100" />
		</el-drawer>
	</div>
</template>
<script lang="ts">
import { getCurrentInstance, toRefs, reactive, computed, nextTick, onUnmounted, ref, onMounted } from 'vue';
import { useStore } from '/@/store/index';
import { initOrgansAndUers, getOutType } from '/@/common';
import { Session } from '/@/utils/storage';
import { ElMessage, ElMessageBox } from 'element-plus';
import storeIndex from '/@/views/system/store/index.vue';
import { openCamera } from '/@/api/hardware/index';
import { queryImgs } from '/@/api/common';
import { debug } from 'console';

export default {
	name: 'BorrowEvidenceList',
	components: { storeIndex },
	props: { outType: String,refForm:ref },
	setup(props: any) {
		const { proxy } = getCurrentInstance() as any;
		const store = useStore();
		const state = reactive({
			outType: props.outType,
			outTypeTitle: getOutType(props.outType as String),
			dialogImageUrl: '',
			dialogVisible: false,
			disabled: false,
			fileList: [],
			drawer: false,
			baseUrl: import.meta.env.VITE_API_URL,
			formInline: {
				receiver: '',
				receiverOrgan: '',
				receiverPhone: '',
				returnTime: null,
				usefulLife: null,
				remark: '',
				location: '',
				imgs: [],
				locationId: 0,
			},
			options: { tqrs: [], tqdws: [] },
			rules: {
				receiverOrgan: [
					{    
						required: true,
						message: '请输入'+getOutType(props.outType as String) + '单位',
						trigger: 'change',
					},
				],
				receiver: [
					{
						required: true,
						message: '请输入'+getOutType(props.outType as String) + '人',
						trigger: 'change',
					},
				],
				receiverPhone: [
					{
						required: true,
						message: '请输入联系电话',
						trigger: 'change',
					},
				],
				location: [
					{
						required: true,
						message: '请选择存放位置',
						trigger: 'blur',
					},
				],
				returnTime: [
					{
						required: true,
						message: '请选择'+(props.outType == '6'?'保存期限':'回库时间'),
						trigger: 'blur',
					},
				],
			},
		});
	
		
		const handleRemove = async (file: any) => {
	
			await ElMessageBox.confirm('此操作将永久删除, 是否继续?', '提示', { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' })
				.then(() => {
					
					var _urlPath='';
					if(file.response) _urlPath=file.response.data;
					else
					_urlPath=file.url;
					debugger
					state.formInline.imgs.pop(_urlPath);
					// debugger
					// for(var i = 0;i<state.fileList.length;i++){
					// 		var _item = state.fileList[i];
					// 		if(_item.url == file.response.data){
					// 			state.fileList.splice(i,i+1);
					// 			break;
					// 		}
					// 	}

						//阻断删除
					//throw new Error();

				})
				.catch(() => {
					throw new Error();
				});
		};
		(function () {
			initOrgansAndUers(state.options, function () {
				const userInfo = Session.get('userInfo');
				state.formInline.receiver = userInfo.userName;
				state.formInline.receiverOrgan = userInfo.organName;
				state.formInline.receiverPhone = userInfo.phone;
			});
		})();
		const customsHeaders = computed(() => {
			return {
				Authorization: `Bearer ${Session.get('token')}`,
			};
		});
		function onSuccess(response: any) {
			if (response.success) {
				
				state.formInline.imgs.push(response.data);
				ElMessage.success('上传成功');
			}
		}
		const handlePictureCardPreview = (file: any) => {
			nextTick(() => {
				var _urlPath='';
					if(file.response) _urlPath=file.response.data;
					else
					_urlPath=file.url;
				state.dialogImageUrl = _urlPath;
				state.dialogVisible = true;
			});
		};
		function onLocation() {
			state.drawer = true;
			proxy.mittBus.on('changeLocation', (data: any) => {
				state.drawer = false;
				state.formInline.location = data.code;
				state.formInline.locationId = data.id;
				proxy.mittBus.off('changeLocation');
			});
		}

		function addimgs(imgsUrl)
		{

			// imgsUrl='http://127.0.0.1:5055/img/202402282129704.jpg';
		if(state.formInline.imgs.length!=state.fileList.length)
		{
           //删除state.fileList
		   state.fileList.splice(0,state.fileList.length);

		   for(var i = 0;i<state.formInline.imgs.length;i++){

				var _name=state.formInline.imgs[i];
				state.fileList.push({name: _name, url: _name });
				}
		}

		   state.formInline.imgs.push(imgsUrl);			
		   state.fileList.push({name: imgsUrl, url: imgsUrl });
		}

		function onCameraInfo() {
			store.dispatch('hardware/getHardwareConfigByKey', 'yjpz_gaopaiyi').then(function (cfg) {
				if (!cfg || !cfg.res1) {
					ElMessage('未配置【高拍仪配置】');
					return;
				}
				var ticks = new Date().getTime();
				console.log(ticks);
				var _typeid = 6;
				var _data = { key: cfg.res1, type: _typeid, relevanceNo: ticks, relevanceId:ticks,url: import.meta.env.VITE_API_URL + '/common/upload/base64img' };
				openCamera(_data);

				ElMessageBox.alert('我们正在打开拍照程序，如果您已经完成拍照，请点击刷新', '', {
				confirmButtonText: '刷新',
				callback: action => {
					queryImgs(ticks,_typeid).then(function(ret){
						if(ret.success){
							for(var i = 0;i<ret.data.length;i++){
								var _item = ret.data[i];
								addimgs(_item.url);
								// state.formInline.imgs.push(_item.url);
								// state.fileList.push({name: _item.url, url: _item.url });
							}
						}
					});
				 }
				});
			});
		}

		onUnmounted(() => {
			proxy.mittBus.off('changeLocation');
		});
		onMounted(() => {});
		const refForm =props.refForm;
		return {
			handleRemove,
			customsHeaders,
			onSuccess,
			handlePictureCardPreview,
			onLocation,
			refForm,
			onCameraInfo,
			addimgs,
			...toRefs(state),
		};
	},
};
</script>
